package pl.edu.agh.thieves.firefly;

import pl.edu.agh.thieves.common.Item;

import java.util.ArrayList;

public class Swarm {

	public void moveFireflies() {
		for (Firefly vocusedFirefly : fireflies) {
			for (Firefly secondFirefly : fireflies)
				if (vocusedFirefly.getBrightness() < secondFirefly.getBrightness())
					vocusedFirefly.moveToward(secondFirefly);
			vocusedFirefly.moveRandomly();
			vocusedFirefly.update();
		}
	}


	public void moveFireflies(int turnNumber) {
		for (int i = 0; i < turnNumber; ++i)
			moveFireflies();
	}

	public double getAnswer(ArrayList<Item> chosenItems) {
		double maxBrightness = 0;
		Coordinates coordinatesOfBrightestFirefly = fireflies[0].getCoordinates();
		for (Firefly firefly : fireflies)
			if (maxBrightness < firefly.getBrightness()) {
				maxBrightness = firefly.getBrightness();
				coordinatesOfBrightestFirefly = firefly.getCoordinates();
			}

		for (int i = 0; i < coordinatesOfBrightestFirefly.getDimension(); ++i) {
			if (coordinatesOfBrightestFirefly.getCoordinateByNumber(i) >= 1)
				chosenItems.add(enviroment.getItem(i));
		}

		//System.out.println(toString());// ////////////////////////////////////

		return maxBrightness;
	}

	@Override
	public String toString() {
		String answer = "Swarm:" + System.lineSeparator();

		for (int i = 0; i < fireflies.length; ++i)
			answer = answer + fireflies[i].toString() + System.lineSeparator();

		return answer;
	}

	public Swarm(int fireflyNumber, Enviroment enviroment) {
		fireflies = new Firefly[fireflyNumber];
		this.enviroment = enviroment;

		for (int i = 0; i < fireflyNumber; ++i)
			fireflies[i] = new Firefly(enviroment);
	}

	private Firefly[] fireflies = null;
	private Enviroment enviroment = null;

}
